#Alexander F. Gazmararian
#afg2@princeton.edu

library(tidyverse)

source("code/fun/book_theme.r")
source("code/fun/savefig.r")

#load union data
union <- readRDS("data/Union_Deidentified.rds")

#load caps-harris national data
caps <- readRDS("data/NatCAPS_20220822.rds")
caps$weight <- caps$nweightNL33D_NEW2
caps$sample <- "National"

#combine samples
unionsub <- subset(union, select = c(sample, wind, weight))
capssub <- subset(caps, select = c(sample, wind, weight))
g <- rbind(unionsub, capssub)

#Create Figure 8.2 ----
plot.unionnat <-
  g %>%
  dplyr::mutate(
    wind = dplyr::recode(
      factor(wind),
      "We should allow new wind farms if the jobs go to local workers" = "Allow new wind if jobs go to local workers",
      "We should stop new wind farm construction to try to protect fossil fuel jobs" = "Stop new wind to protect fossil fuel jobs",
      "We should allow new wind farms no matter who gets the jobs" = "Allow new wind no matter who gets jobs"
    )
  ) %>%
  dplyr::group_by(sample, wind) %>%
  dplyr::summarise(n = sum(weight)) %>%
  dplyr::group_by(sample) %>%
  dplyr::mutate(pct = prop.table(n)) %>%
  ggplot(aes(x=wind, y=pct, fill=sample, color=sample, label=scales::percent(pct,accuracy=1))) +
  geom_col(position = position_dodge2(width=.9, preserve = "single")) +
  geom_text(position = position_dodge(.9), hjust=-.5, size = 3, color = "black", aes(group = sample)) +
  book_theme +
  coord_flip() +
  scale_fill_grey() +
  scale_color_grey() +
  scale_y_continuous(labels = scales::percent, expand = c(0,0), limits = c(0,.7)) +
  scale_x_discrete(labels = scales::label_wrap(25)) +
  labs(y="", x = "", fill="", color = "") +
  theme(legend.box.margin = margin(t=-15))
plot.unionnat
savefig(plot.unionnat, "8.2_figure_unionlocaljobs", height = 2.5, filepath = "figures/")

# Solar in online appendix----
plot.solar <-
  caps %>%
  tidyr::pivot_longer(cols = c(wind, solar)) %>%
  dplyr::mutate(value = gsub("wind farms|solar farms", "projects", value),
                value = gsub("wind farm|solar farm", "renewable", value),
                name = ifelse(name == "solar", "Solar", "Wind")) %>%
  ggplot() +
  geom_bar(aes(x=value, y=after_stat(prop), group=name, fill=name, weight=weight), position = "dodge") +
  book_theme +
  coord_flip() +
  scale_fill_grey() +
  scale_y_continuous(labels = scales::percent, expand = c(0,0)) +
  scale_x_discrete(labels = scales::label_wrap(25)) +
  labs(y="", x = "", fill="")
plot.solar
savefig(plot.solar, filename = "si_localjobs_solar", filepath = "figures/ch8/", height = 2.5)

